package com.my.demo.oauthService.service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.sql.DataSource;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate;

public class RedisResourceService {

	private RedisTemplate<String, Map<String, List<String>>> redisTemplate;
	private DataSource dataSource;
	static final String AUTH_TO_RESOURCE = "auth_resource:";

	public RedisResourceService(DataSource _dataSource,
			RedisTemplate<String, Map<String, List<String>>> _redisTemplate) {
		this.dataSource = _dataSource;
		this.redisTemplate = _redisTemplate;
		initData();
	}

	@SuppressWarnings("unchecked")
	private void initData() {
		JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
		Map<String, List<String>> resourceRolesMap = new TreeMap<>();
		List<Map<String, Object>> list = jdbcTemplate.queryForList(
				"SELECT CONCAT(\"/\",b.service,b.url) AS url,GROUP_CONCAT(c.name) AS role_names from rbac_role_resource a left join rbac_resource b ON a.resource_id = b.id left join rbac_role c ON a.role_id = c.id GROUP BY b.url");

		for (Map<String, Object> m : list) {
			System.out.print(m.get("url").toString());
			resourceRolesMap.put(m.get("url").toString(), Arrays.asList(m.get("role_names").toString().split(",")));
		}
		redisTemplate.opsForHash().putAll(AUTH_TO_RESOURCE, resourceRolesMap);
		// System.out.print("******************************set_ResourcePath");
	}
}
